package com.genius.adminmanager.user.service.impl;

import java.sql.SQLException;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.genius.adminmanager.menu.entity.MenuJson;
import com.genius.adminmanager.menu.service.MenuUtils;
import com.genius.adminmanager.other.entity.ResponseJson;
import com.genius.adminmanager.other.entity.SessionJson;
import com.genius.adminmanager.user.entity.UserJson;
import com.genius.adminmanager.user.service.UserServiceAdapter;
import com.genius.workflow.page.PageResult;
import com.genius.workflow.page.SearchResult;
import com.genius.workflow.page.SqlLang;
import com.genius.workflow.util.ConnectionException;
import com.genius.workflow.util.DBClosedException;
import com.genius.workflow.util.DBTools2;
import com.genius.workflow.util.DBUtils;
import com.genius.workflow.util.GeniusJsonUtil;

@Service("userSelectService")
public class UserSelectServiceImpl extends UserServiceAdapter{

	@Override
	public JSONObject getSelectHead(JSONObject json, HttpSession session,JSONObject response) {
		 String menuId = json.getString(MenuJson.menuId);
	        
        String roleId = (String)session.getAttribute(SessionJson.roleId);
        
        if(roleId == null){
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_Session_Failure);
            return response;
        }
        
        response = MenuUtils.getPowerFileByMenu(roleId,menuId, response);
        
        JSONObject result =  response.getJSONObject(ResponseJson.data);
        if(result == null){
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_No_Porwer_Query_Field);
            return response;
        }
        return response;
	}

	@Override
	public JSONObject getSelectBody(JSONObject json, JSONObject response) {
//		System.out.println(json);
		int limit = json.getIntValue(PageResult.limit);
        int page = json.getIntValue(PageResult.page);
        SqlLang sql = null;
        String headField = json.getString(PageResult.headField);
        String selectSB = "SELECT userId,username,a.name,password,command,sex,phone,mail,createTime,a.status,groupId"
        		+ ",(select group_concat(name)name from t_group where find_in_set(groupId,a.groupId)) groupname,jobnumber,remark,company FROM t_user a ${where}";
        if(headField == null){
        	headField = "groupname,groupId,userId,username,password,command,name,sex,phone,mail,status,jobnumber,remark,company";
        }
        //参数的json
        JSONObject parmeterJson = new JSONObject();
//        parmeterJson.put(UserJson.userId, "000");
        //普通查询的条件及字段值json
        SearchResult  searchResult = DBTools2.getWhereFieldBySearch(json);
        //高级查询的条件及字段值json
        SearchResult  highSearchResult = DBTools2.getWhereFieldByHighSearch(json);
        //普通查询条件与高级查询条件有且只有一个是 真实存在的，不可能两个同时查询
        //合并所有的结果值统一到一个json中
        JSONObject mergeJson = DBTools2.mergeAll(parmeterJson, searchResult, highSearchResult);
        //进行排序
        if(json.containsKey(PageResult.asc)){
            String ascField = json.getString(PageResult.ascField);
            String asc = json.getString(PageResult.asc);
           
            sql = DBTools2.getSelectPageSql(headField,selectSB,page,limit,ascField,asc,searchResult.getSearchWhere(),highSearchResult.getSearchWhere());
            
        }else{
        	 String asc = "desc";
             String ascField = UserJson.createTime;
             sql = DBTools2.getSelectPageSql(headField,selectSB,page,limit,ascField,asc,searchResult.getSearchWhere(),highSearchResult.getSearchWhere());
        }
        try {
        	String parameterArr [] = DBTools2.parsePermeterBySql(sql.getSourceSql(), mergeJson);
            PageResult result = DBUtils.selectByCount(sql,parameterArr);
            JSONArray data = (JSONArray)result.getData();
            for(int i =0;i<data.size();i++){
                GeniusJsonUtil.convertResource(data.getJSONObject(i),UserJson.resource);
            }
            response.put(ResponseJson.count, result.getCount());
            response.put(ResponseJson.data, data);
            
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            
        } catch (ConnectionException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
        } catch (DBClosedException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
        } catch (SQLException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
        }
		return response;
	}
	@Override
	public JSONObject getphoto(JSONObject json, JSONObject response) {
		JSONObject searchJson = json.getJSONObject("search");
		String nameString="";
		if (searchJson!= null && searchJson.getString("name") != null) {
			nameString = " and name like '%" + searchJson.getString("name") + "%'";
		}
		int limit = json.getIntValue(PageResult.limit);
        int page = json.getIntValue(PageResult.page);
		SqlLang sql = null;
        String selectSB = " select userId,username,name,phone,photo from t_user where 1=1  "+nameString;
        String headField = "*";
		SearchResult  searchResult = new SearchResult();
		JSONObject mergeJson = new JSONObject();
		String asc = null;
		String ascField = null;
		sql = DBTools2.getSelectPageSql(headField,selectSB,page,limit,ascField,asc,searchResult.getSearchWhere());
        try {
			String parameterArr [] = DBTools2.parsePermeterBySql(sql.getSourceSql(), mergeJson);
			PageResult result = DBTools2.selectByCount(sql,parameterArr);
			JSONArray data = (JSONArray)result.getData();
			response.put(ResponseJson.count, result.getCount());
			response.put(ResponseJson.data, data);
			response.put(ResponseJson.status, ResponseJson.status_Success);
        } catch (ConnectionException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
        } catch (DBClosedException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
        } catch (SQLException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
        }
		return response;
	}
	@Override
	public JSONObject getpassword(JSONObject json, JSONObject response) {
		JSONObject searchJson = json.getJSONObject("search");
		String nameString="";
		if (searchJson!= null && searchJson.getString("name") != null) {
			nameString = " and name like '%" + searchJson.getString("name") + "%'";
		}
		int limit = json.getIntValue(PageResult.limit);
        int page = json.getIntValue(PageResult.page);
		SqlLang sql = null;
        String selectSB = " select userId,username,name,phone,password from t_user where 1=1  "+nameString;
        String headField = "*";
		SearchResult  searchResult = new SearchResult();
		JSONObject mergeJson = new JSONObject();
		String asc = null;
		String ascField = null;
		sql = DBTools2.getSelectPageSql(headField,selectSB,page,limit,ascField,asc,searchResult.getSearchWhere());
        try {
			String parameterArr [] = DBTools2.parsePermeterBySql(sql.getSourceSql(), mergeJson);
			PageResult result = DBTools2.selectByCount(sql,parameterArr);
			JSONArray data = (JSONArray)result.getData();
			response.put(ResponseJson.count, result.getCount());
			response.put(ResponseJson.data, data);
			response.put(ResponseJson.status, ResponseJson.status_Success);
        } catch (ConnectionException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_DB_Connect_Failed);
        } catch (DBClosedException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
            response.put(ResponseJson.msg, ResponseJson.msg_DB_Closed_Failed);
        } catch (SQLException e) {
            response.put(ResponseJson.status, ResponseJson.status_Failed);
			response.put(ResponseJson.msg, ResponseJson.msg_Query_Data_Error);
        }
		return response;
	}
}
